#!/usr/bin/env python3
"""
Simple Audio File Generator for Pomodoro Timer
Creates basic audio files using sine waves
"""

import math
import wave
import struct
import os

def generate_sine_wave(frequency, duration, sample_rate=44100, amplitude=0.3):
    """Generate a sine wave with given parameters"""
    frames = int(duration * sample_rate)
    wave_data = []
    
    for i in range(frames):
        t = i / sample_rate
        # Generate sine wave with fade in/out to avoid clicks
        fade_frames = int(0.05 * sample_rate)  # 50ms fade
        fade_factor = 1.0
        
        if i < fade_frames:
            fade_factor = i / fade_frames
        elif i > frames - fade_frames:
            fade_factor = (frames - i) / fade_frames
            
        value = amplitude * fade_factor * math.sin(2 * math.pi * frequency * t)
        wave_data.append(value)
    
    return wave_data

def generate_chord(frequencies, duration, sample_rate=44100, amplitude=0.2):
    """Generate a chord by combining multiple frequencies"""
    frames = int(duration * sample_rate)
    wave_data = [0.0] * frames
    
    for freq in frequencies:
        sine_wave = generate_sine_wave(freq, duration, sample_rate, amplitude / len(frequencies))
        for i in range(frames):
            wave_data[i] += sine_wave[i]
    
    return wave_data

def save_wav_file(filename, wave_data, sample_rate=44100):
    """Save wave data to a WAV file"""
    with wave.open(filename, 'w') as wav_file:
        wav_file.setnchannels(1)  # Mono
        wav_file.setsampwidth(2)  # 16-bit
        wav_file.setframerate(sample_rate)
        
        # Convert float data to 16-bit integers
        for sample in wave_data:
            # Clamp to [-1, 1] and convert to 16-bit
            sample = max(-1.0, min(1.0, sample))
            wav_file.writeframes(struct.pack('<h', int(sample * 32767)))

def create_bell_sound():
    """Create a bell-like sound"""
    # Bell sound with harmonics
    wave_data = []
    
    # Main tone
    main_wave = generate_sine_wave(800, 0.3, amplitude=0.4)
    wave_data.extend(main_wave)
    
    # Short pause
    pause = [0.0] * int(0.1 * 44100)
    wave_data.extend(pause)
    
    # Higher tone
    high_wave = generate_sine_wave(1000, 0.2, amplitude=0.3)
    wave_data.extend(high_wave)
    
    # Short pause
    wave_data.extend(pause)
    
    # Final tone
    final_wave = generate_sine_wave(800, 0.4, amplitude=0.4)
    wave_data.extend(final_wave)
    
    return wave_data

def create_chime_sound():
    """Create a chime-like sound"""
    # Chime with pleasant chord progression
    wave_data = []
    
    # C major chord notes: C5, E5, G5
    chord1 = generate_chord([523.25, 659.25, 783.99], 0.8, amplitude=0.3)
    wave_data.extend(chord1)
    
    # Short pause
    pause = [0.0] * int(0.2 * 44100)
    wave_data.extend(pause)
    
    # Another chord
    chord2 = generate_chord([659.25, 783.99], 0.8, amplitude=0.25)
    wave_data.extend(chord2)
    
    # Final chord
    wave_data.extend(pause)
    chord3 = generate_chord([523.25, 659.25, 783.99], 1.2, amplitude=0.3)
    wave_data.extend(chord3)
    
    return wave_data

def create_ding_sound():
    """Create a ding sound"""
    wave_data = []
    
    # Quick high-pitched ding
    ding1 = generate_sine_wave(1200, 0.15, amplitude=0.35)
    wave_data.extend(ding1)
    
    # Short pause
    pause = [0.0] * int(0.05 * 44100)
    wave_data.extend(pause)
    
    # Second ding
    ding2 = generate_sine_wave(1500, 0.25, amplitude=0.25)
    wave_data.extend(ding2)
    
    return wave_data

def create_notification_sound():
    """Create a notification sound"""
    wave_data = []
    
    # Modern notification pattern
    frequencies = [600, 800, 1000, 800]
    durations = [0.2, 0.2, 0.3, 0.3]
    
    for i, freq in enumerate(frequencies):
        tone = generate_sine_wave(freq, durations[i], amplitude=0.3 + i * 0.025)
        wave_data.extend(tone)
        
        if i < len(frequencies) - 1:
            pause = [0.0] * int(0.1 * 44100)
            wave_data.extend(pause)
    
    return wave_data

def create_gentle_sound():
    """Create a gentle sound"""
    wave_data = []
    
    # Very soft and gentle tones
    # A4 and C#5 for a pleasant interval
    gentle1 = generate_sine_wave(440, 1.0, amplitude=0.2)
    wave_data.extend(gentle1)
    
    # Long pause
    pause = [0.0] * int(0.3 * 44100)
    wave_data.extend(pause)
    
    # Higher gentle tone
    gentle2 = generate_sine_wave(554.37, 1.5, amplitude=0.15)
    wave_data.extend(gentle2)
    
    return wave_data

def create_success_sound():
    """Create a success sound"""
    wave_data = []
    
    # Ascending success pattern: C5, E5, G5, C6
    frequencies = [523.25, 659.25, 783.99, 1046.50]
    durations = [0.2, 0.2, 0.2, 0.6]
    
    for i, freq in enumerate(frequencies):
        tone = generate_sine_wave(freq, durations[i], amplitude=0.3 + i * 0.05)
        wave_data.extend(tone)
        
        if i < len(frequencies) - 1:
            pause = [0.0] * int(0.05 * 44100)
            wave_data.extend(pause)
    
    return wave_data

def main():
    """Generate all audio files"""
    sounds_dir = "assets/sounds"
    
    # Create directory if it doesn't exist
    os.makedirs(sounds_dir, exist_ok=True)
    
    # Generate all sounds
    sounds = {
        'bell': create_bell_sound,
        'chime': create_chime_sound,
        'ding': create_ding_sound,
        'notification': create_notification_sound,
        'gentle': create_gentle_sound,
        'success': create_success_sound
    }
    
    for sound_name, sound_func in sounds.items():
        print(f"Generating {sound_name}.wav...")
        wave_data = sound_func()
        filename = os.path.join(sounds_dir, f"{sound_name}.wav")
        save_wav_file(filename, wave_data)
        print(f"Created {filename}")
    
    print("\nAll audio files generated successfully!")
    print("Note: These are WAV files. You may want to convert them to MP3 for smaller file sizes.")

if __name__ == "__main__":
    main()
